package com.ruoyi.express.controller;

import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.express.domain.AppExpressDelivery;
import com.ruoyi.express.service.IAppExpressDeliveryService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.json.JSON;
import com.ruoyi.common.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import org.springframework.web.multipart.MultipartFile;
/**
 * 快递单据Controller
 * 
 * @author ruoyi
 * @date 2019-12-03
 */
@Controller
@RequestMapping("/express/delivery")
public class AppExpressDeliveryController extends BaseController
{
    private String prefix = "express/delivery";

    @Autowired
    private IAppExpressDeliveryService appExpressDeliveryService;

    @RequiresPermissions("express:delivery:view")
    @GetMapping()
    public String delivery()
    {
        return prefix + "/delivery";
    }

    /**
     * 查询快递单据列表
     */
    @RequiresPermissions("express:delivery:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(AppExpressDelivery appExpressDelivery)
    {
        startPage();
        List<AppExpressDelivery> list = appExpressDeliveryService.selectAppExpressDeliveryList(appExpressDelivery);
        return getDataTable(list);
    }

    /**
     * 导出快递单据列表
     */
    @RequiresPermissions("express:delivery:export")
    @Log(title = "快递单据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(AppExpressDelivery appExpressDelivery)
    {
        List<AppExpressDelivery> list = appExpressDeliveryService.selectAppExpressDeliveryList(appExpressDelivery);
        ExcelUtil<AppExpressDelivery> util = new ExcelUtil<AppExpressDelivery>(AppExpressDelivery.class);
        return util.exportExcel(list, "delivery");
    }

    /**
     * 新增快递单据
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存快递单据
     */
    @RequiresPermissions("express:delivery:add")
    @Log(title = "快递单据", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(AppExpressDelivery appExpressDelivery)
    {
        return toAjax(appExpressDeliveryService.insertAppExpressDelivery(appExpressDelivery));
    }

    /**
     * 修改快递单据
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        AppExpressDelivery appExpressDelivery = appExpressDeliveryService.selectAppExpressDeliveryById(id);
        mmap.put("appExpressDelivery", appExpressDelivery);
        return prefix + "/edit";
    }

    /**
     * 修改保存快递单据
     */
    @RequiresPermissions("express:delivery:edit")
    @Log(title = "快递单据", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(AppExpressDelivery appExpressDelivery)
    {
        return toAjax(appExpressDeliveryService.updateAppExpressDelivery(appExpressDelivery));
    }

    /**
     * 删除快递单据
     */
    @RequiresPermissions("express:delivery:remove")
    @Log(title = "快递单据", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(appExpressDeliveryService.deleteAppExpressDeliveryByIds(ids));
    }

    @Log(title="图片识别", businessType=BusinessType.INSERT)
    @PostMapping({"/add1"})
    @ResponseBody
    public String addSave1(MultipartFile upload, String fileName, String user) {
        String urlPre = "/profile/upload/";
        String[] fileNames = fileName.split("\\.");
        int sizef = fileNames.length;
        fileName = fileNames[(sizef - 2)] + "." + fileNames[(sizef - 1)];

        System.out.println("addSave2 fileName:" + fileName);
        System.out.println("addSave2 user:" + user);
        try
        {
            File imgf = new File(urlPre + fileName);

            upload.transferTo(imgf);

            while (!imgf.exists()) {
                try {
                    Thread.sleep(100L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            String resultStr;
            Socket socket = null;
            try {
                AppExpressDelivery appResnetPic = new AppExpressDelivery();

                socket = getConnection("127.0.0.1", 8122);
                socket.setSoTimeout(10000);
                resultStr = send(socket, urlPre + fileName);
                System.out.println("socket resultStr=" + resultStr);
                String str = resultStr.trim().replaceAll("'", "\"");
                JSONObject data = (JSONObject)JSON.unmarshal(str, JSONObject.class);

                String type1 = data.getStr("type1");
                String type2 = data.getStr("type2");
                String value1 = data.getStr("value1");
                String value2 = data.getStr("value2");

                appResnetPic.setPicLocation(urlPre + fileName);
                appResnetPic.setType1(type1);
                appResnetPic.setType2(type2);
                appResnetPic.setValue1(value1);
                appResnetPic.setValue2(value2);
                if (this.appExpressDeliveryService.insertAppExpressDelivery(appResnetPic) > 0)
                    return value1 + " | " + value2;
            }
            catch (Exception e)
            {
                e.printStackTrace();
                System.out.println("image file path：" + fileName);
                return "error, Failed to link remote service。";
            } finally {
                close(socket);
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return "error";
    }

    @Log(title="图片识别", businessType=BusinessType.INSERT)
    @PostMapping({"/add2"})
    @ResponseBody
    public AjaxResult addSave2(MultipartFile upload, String fileName, String user)
    {
        String[] fileNames = fileName.split("\\.");
        int sizef = fileNames.length;
        fileName = fileNames[(sizef - 2)] + "." + fileNames[(sizef - 1)];
        System.out.println("addSave2 fileName:" + fileName);
        System.out.println("addSave2 user:" + user);
        try
        {
            File imgf = new File("/profile/upload/" + fileName);

            upload.transferTo(imgf);

            return success();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return error();
    }

    @Log(title="图片识别", businessType=BusinessType.INSERT)
    @PostMapping({"/add3"})
    @ResponseBody
    public AjaxResult addSave3(String fileName)
    {
        System.out.println("addSave3 fileName:" + fileName);

        File imgfnew = new File("/profile/upload/" + fileName);

        while (!imgfnew.exists()) {
            try {
                Thread.sleep(100L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
        String resultStr;
        Socket socket = null;
        try {
            AppExpressDelivery appResnetPic = new AppExpressDelivery();

            socket = getConnection("127.0.0.1", 8122);
            socket.setSoTimeout(10000);
            resultStr = send(socket, "/profile/upload/" + fileName);
            System.out.println("socket resultStr=" + resultStr);
            String str = resultStr.trim().replaceAll("'", "\"");
            JSONObject data = (JSONObject)JSON.unmarshal(str, JSONObject.class);

            String type1 = data.getStr("type1");
            String type2 = data.getStr("type2");
            String value1 = data.getStr("value1");
            String value2 = data.getStr("value2");

            appResnetPic.setPicLocation("/profile/upload/" + fileName);
            appResnetPic.setType1(type1);
            appResnetPic.setType2(type2);
            appResnetPic.setValue1(value1);
            appResnetPic.setValue2(value2);
            if (this.appExpressDeliveryService.insertAppExpressDelivery(appResnetPic) > 0)
                return success();
        }
        catch (Exception e)
        {

            e.printStackTrace();
            System.out.println("image file path：" + fileName);
            return AjaxResult.error("error, Failed to link remote service。");
        } finally {
            close(socket);
        }
        return error();
    }

    public Socket getConnection(String ip, int port)
    {
        Socket socket = null;
        try {
            socket = new Socket(ip, port);
            socket.setSoTimeout(30000);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return socket;
    }

    public String send(Socket socket, String cmd)
    {
        InputStream in = null;
        OutputStream out = null;
        BufferedReader br = null;
        try
        {
            in = socket.getInputStream();

            out = socket.getOutputStream();

            PrintWriter printWriter = new PrintWriter(out, true);
            printWriter.write(cmd);
            printWriter.flush();

            br = new BufferedReader(new InputStreamReader(in));
            return br.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public void close(Socket socket)
    {
        if (socket != null)
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
    }
}
